//
//  MyContactVCModel.m
//  Yihubang
//
//  Created by hyu on 16/8/5.
//  Copyright © 2016年 jinghao. All rights reserved.
//

#import "MyContactVCModel.h"
#import "MyContactCell.h"
@interface MyContactVCModel ()
@property (nonatomic, strong) UIView * addContratFooterView;
@property (nonatomic, strong) UIButton * addContrat;
//@property (nonatomic, strong) RACCommand *sendMessageCommend;
@property (nonatomic, strong) RACCommand *changeSortCommend;
@property (nonatomic, assign) BOOL  isChanged;
@end

@implementation MyContactVCModel
- (void)initialize
{
    [super initialize];
    //    [[self.requestRemoteDataCommand execute:nil] subscribeNext:^(id x) {
    //        NSLog(@"======111 ==== %@",x);
    //    }];
    @weakify(self);
    [[RACObserve(self, dataSource) filter:^(NSArray * data){
        return @(data.count >0).boolValue;
    }] subscribeNext:^(NSArray * show){
        @strongify(self)
        if([show[0] count] > 0){
            self.mTableView.tableFooterView.height= 119.f;
        }else{
            self.mTableView.tableFooterView.height=ScreenHeight - 120.f;
        }
    }];
    self.changeSortCommend = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self)
        if(self.isChanged){
            [[self.httpService changeContractSort:[self sortMyContract] resultClass:nil] subscribeNext:^(BaseModel *model){
                @strongify(self)
                if (model.code==200) {
                    [self.viewController hiddenHUDWithString:@"修改完成" error:NO];
                }else {
                    [self.viewController hiddenHUDWithString:@"修改失败" error:NO];
                }
            }];

        }
        return [RACSignal empty];
    }];

}
-(NSMutableArray *)sortMyContract{
    NSMutableArray * contract = [NSMutableArray array];
    NSInteger count = [self.dataSource[0] count];
    for (NSMutableDictionary * contractInfo in self.dataSource[0]) {
        [contractInfo setObject:[NSNumber numberWithInteger:count] forKey:@"sort"];
        [contract addObject:contractInfo];
        count --;
    }
    return contract;
}
- (void)bindTableView:(UITableView *)tableView
{
    [super bindTableView:tableView];
    self.mTableView.tableFooterView=self.addContratFooterView;
    self.cellReuseIdentifier = @"MyContactCell";
    [self.mTableView registerCellWithReuseIdentifier:@"MyContactCell"];
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureRecognized:)];
    [self.mTableView addGestureRecognizer:longPress];
//    self.shouldMoreToRefresh = YES;
    self.shouldPullToRefresh = YES;
//    self.pageSize = @(10);
}

- (RACSignal*)requestRemoteDataSignalWithPage:(NSUInteger)page
{
    RACSignal *fetchSignal = [self.httpService queryContactList:nil];
    //    return fetchSignal;
    @weakify(self);
    return [[[fetchSignal collect] doNext:^(id x) {
        NSLog(@"===== x %@",x);
        @strongify(self);
        self.mTableView.loading =YES;
        self.mTableView.loadedImageName =@"窗户";
        self.mTableView.descriptionText=@"立即添加，保障我的安全";
        if(self.mTableView.mj_footer.isRefreshing ){
            [self.mTableView.mj_footer endRefreshing];
        }
        if (self.mTableView.mj_header.isRefreshing) {
            [self.mTableView.mj_header endRefreshing];
        }       
    }] map:^id(NSArray *responses) {
        NSLog(@"===== value  %@",responses);
        @strongify(self);
        BaseModel *model = responses.firstObject;
        NSMutableArray * array = [NSMutableArray new];
        if (model.code==200) {
            array=model.data;
            self.dataSource=@[array];
            [self.mTableView reloadData];
        }else{
        }
        return array;
        return nil;
        
    }];
}
- (void)configureCell:(MyContactCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(id)object
{
//    [cell showNewsDetial:object];
    cell.name.text =object[@"name"];
    if(indexPath.row ==0){
        cell.contactSequence.text = [NSString stringWithFormat:@"第%@时间需要TA",[self changeNumTocha:indexPath.row+1]];
    }else{
        cell.contactSequence.text = [NSString stringWithFormat:@"%ld 需要TA",indexPath.row+1];
    }
    [cell.notificationHim addTarget:self action:@selector(sendMessage:) forControlEvents:UIControlEventTouchUpInside];
    cell.notificationHim.tag =indexPath.row;
}
-(void)sendMessage :(id) sender{
    NSInteger row =[sender tag];
    [self.viewController showMessageView:@[self.dataSource[0][row][@"phone"]] title:@"通知" body:@"我正在使用闪护女神保护自己,已经设置您为紧急联系人，可前往http://itunes.apple.com/us/app/id1188583750下载"];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Mine" bundle:[NSBundle mainBundle]];
    UIViewController *vct = [story instantiateViewControllerWithIdentifier:@"AddContactViewController"];
    vct.params =@{@"info":self.dataSource[0][indexPath.row],@"count":[NSNumber numberWithInteger:[self.dataSource[0] count]]};
     @weakify(self);
    [vct setCallbackBlock:^(id callBackData) {
        @strongify(self);
        [self first];
    }];
    [self.viewController.navigationController pushViewController:vct animated:YES];

}
//要求委托方的编辑风格在表视图的一个特定的位置。
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCellEditingStyle result = UITableViewCellEditingStyleNone;//默认没有编辑风格
    result = UITableViewCellEditingStyleDelete;//设置编辑风格为删除风格
    return result;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{//请求数据源提交的插入或删除指定行接收者。
    if (editingStyle ==UITableViewCellEditingStyleDelete) {//如果编辑样式为删除样式
        if([self.dataSource[0] count] ==0){
            [self.viewController hiddenHUDWithString:@"至少需要一位紧急联系人" error:NO];
        }else{
            [[[HttpManagerCenter sharedHttpManager] deleteContact:self.dataSource[0][indexPath.row][@"cid"] resultClass:nil] subscribeNext:^(BaseModel *model){
                if(model.code ==200){
                    [self.dataSource[0] removeObjectAtIndex:indexPath.row];//移除数据源的数据
//                    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];//移除tableView中的数据
                    [self.mTableView reloadData];
                }
            }];
        }
    }
}
- (void)longPressGestureRecognized:(id)sender {
    UILongPressGestureRecognizer *longPress = (UILongPressGestureRecognizer *)sender;
    UIGestureRecognizerState state = longPress.state;
    CGPoint location = [longPress locationInView:self.mTableView];
    NSIndexPath *indexPath = [self.mTableView indexPathForRowAtPoint:location];
    static UIView       *snapshot = nil;        ///< A snapshot of the row user is moving.
    static NSIndexPath  *sourceIndexPath = nil; ///< Initial index path, where gesture begins.
    switch (state) {
        case UIGestureRecognizerStateBegan: {
            if (indexPath) {
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
                sourceIndexPath = indexPath;
                UITableViewCell *cell = [self.mTableView cellForRowAtIndexPath:indexPath];
                // Take a snapshot of the selected row using helper method.
                snapshot = [self customSnapshoFromView:cell];
                // Add the snapshot as subview, centered at cell's center...
                __block CGPoint center = cell.center;
                snapshot.center = center;
                snapshot.alpha = 0.0;
                [self.mTableView addSubview:snapshot];
                [UIView animateWithDuration:0.25 animations:^{
                    
                    // Offset for gesture location.
                    center.y = location.y;
                    snapshot.center = center;
                    snapshot.transform = CGAffineTransformMakeScale(1.02, 1.02);
                    snapshot.alpha = 1.0f;
                    cell.alpha = 0.0;
                    cell.hidden = YES;
                }];
            }
            break;
        }
        case UIGestureRecognizerStateChanged: {
            CGPoint center = snapshot.center;
            center.y = location.y;
            snapshot.center = center;
            // Is destination valid and is it different from source?
            if (indexPath && ![indexPath isEqual:sourceIndexPath]) {
                // ... update data source.
                [self.dataSource[0] exchangeObjectAtIndex:indexPath.row withObjectAtIndex:sourceIndexPath.row];
                // ... move the rows.
                [self.mTableView moveRowAtIndexPath:sourceIndexPath toIndexPath:indexPath];
                sourceIndexPath = indexPath;//上下移动sourceIndexPath 旧替换新
                [self setIsChanged:YES];
            }
            break;
        }
        default: {
            // Clean up.
            UITableViewCell *cell = [self.mTableView cellForRowAtIndexPath:sourceIndexPath];
            cell.alpha = 0.0;
            [UIView animateWithDuration:0.25 animations:^{
                snapshot.center = cell.center;
                snapshot.transform = CGAffineTransformIdentity;
                snapshot.alpha = 0.0;
                cell.alpha = 1.0;
            } completion:^(BOOL finished) {
                cell.hidden = NO;
                [snapshot removeFromSuperview];
                snapshot = nil;
                [self.mTableView reloadData];//更新排序
                sourceIndexPath = nil;
            }];
            break;
        }
    }
}

#pragma mark - Helper methods

/** @brief Returns a customized snapshot of a given view. */
- (UIView *)customSnapshoFromView:(UIView *)inputView {
    
    // Make an image from the input view.
    UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, NO, 0);
    [inputView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    // Create an image view.
    UIView *snapshot = [[UIImageView alloc] initWithImage:image];
    snapshot.layer.masksToBounds = NO;
    snapshot.layer.cornerRadius = 0.0;
    snapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0);
    snapshot.layer.shadowRadius = 5.0;
    snapshot.layer.shadowOpacity = 0.4;
    return snapshot;
}


-(NSString *)changeNumTocha:(NSInteger)num {
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = kCFNumberFormatterRoundHalfDown;
    NSString *string = [formatter stringFromNumber:[NSNumber numberWithInteger:num]];
    return string;
}

#pragma mark - setView
- (UIView*)addContratFooterView
{
    if (!_addContratFooterView) {
        _addContratFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 119)];
//        _addContratFooterView.backgroundColor =[UIColor yellowColor];
        [_addContratFooterView addSubview:self.addContrat];
        [self.addContrat mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(_addContratFooterView.mas_centerX);
            make.bottom.equalTo(_addContratFooterView.mas_bottom).with.offset(0);
//            make.height.equalTo(@30);
//            make.width.equalTo(@132);
        }];
    }
    return _addContratFooterView;
}
- (UIButton*)addContrat
{
    if (!_addContrat) {
        _addContrat = [UIButton buttonWithType:UIButtonTypeCustom];
//        [_addContrat setTitle:@"添加新的联系人" forState:UIControlStateNormal];
//        _addContrat.titleLabel.font = [UIFont systemFontOfSize:15.0f];
//        [_addContrat setCornerRadius:5.f];
//        [_addContrat setTitleColor:[UIColor colorWithHex:0xffffff] forState:UIControlStateNormal];
        [_addContrat  setImage:[UIImage imageNamed:@"addNewContract"] forState:UIControlStateNormal];
        @weakify(self)
        [[_addContrat rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self);
            UIStoryboard *story = [UIStoryboard storyboardWithName:@"Mine" bundle:[NSBundle mainBundle]];
            UIViewController *vct = [story instantiateViewControllerWithIdentifier:@"AddContactViewController"];
            [vct setCallbackBlock:^(id callBackData) {
                [self first];
            }];
            [self.viewController.navigationController pushViewController:vct animated:YES];

        }];
    }
    return _addContrat;
}
@end
